//引入小仓库
import { defineStore } from 'pinia'
//引入用户接口
import { UserLogin, GetUserInfo, UserLoginOut } from '@/api/user'
//引入路由信息
import { contantRouter } from '@/router/routers'
//引入类型
import type { UserState } from './types/type'

//引入本地存储的工具方法
import { GET_TOKEN, SET_TOKEN, DELETE_TOKEN } from '@/utils/token'
import {
  UserLoginResponseData,
  UserLoginRequestData,
  UserInfoResponseData,
} from '@/api/user/type'

const useUserStore = defineStore('user', {
  //保存仓库数据
  state: (): UserState => {
    return {
      token: GET_TOKEN(),
      menuRouters: contantRouter,
      userName: '',
      avatar: '',
    }
  },
  getters: {},
  //逻辑|异步
  actions: {
    //用户登陆
    async userLogin(data: UserLoginRequestData) {
      //登陆请求
      const result: UserLoginResponseData = await UserLogin(data)
      //登陆请求：成功200 -> token
      //登陆请求：失败201 登陆失败错误信息
      if (result.code == 200) {
        this.token = result.data
        SET_TOKEN(result.data)
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    //获取用户信息
    async getUserInfo() {
      const result: UserInfoResponseData = await GetUserInfo()
      if (result.code == 200) {
        this.userName = result.data.name
        this.avatar = result.data.avatar
        return 'ok'
      } else {
        return Promise.reject(result.message)
      }
    },
    //用户退出
    async userLoginOut() {
      const result: any = await UserLoginOut()
      if (result.code == 200) {
        this.token = ''
        this.avatar = ''
        this.userName = ''
        DELETE_TOKEN()
        return 'ok'
      } else {
        return Promise.reject(result.message)
      }
    },
  },
})

export default useUserStore
